package com.ahui.ydd.controller;

import com.ahui.ydd.Vo.*;
import com.ahui.ydd.Vo.HotVo;
import com.ahui.ydd.Vo.NewVo;
import com.ahui.ydd.Vo.YddArticleVo;
import com.ahui.ydd.Vo.ProFileVo;
import com.ahui.ydd.common.CustomException;
import com.ahui.ydd.common.R;
import com.ahui.ydd.common.ResultData;
import com.ahui.ydd.dto.PageDto;
import com.ahui.ydd.entity.*;
import com.ahui.ydd.service.*;
import com.ahui.ydd.dto.ShowDto;
import com.ahui.ydd.dto.YddArticleDto;
import com.ahui.ydd.entity.*;
import com.ahui.ydd.service.*;
import com.ahui.ydd.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/index")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddUserDataService yddUserDataService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<Map> login(@RequestBody Map map) {
        log.info("获取用户输入数据" + map.get("mobile") + map.get("password"));

        Object mobile = map.get("mobile");
        //接收前端发来的密码  将密码经md5处理
        String password = (String) map.get("password");
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //select * from sys_user where phone = ? and password = ? ;
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(mobile != null, SysUser::getLoginName, mobile)
                .eq(password != null, SysUser::getPassword, password);

        //执行方法查询
        SysUser user = loginService.getOne(queryWrapper);

        //判断数据是否存在
        if (user != null) {
            //判断用户是都被冻结 1 正常 0 冻结
            if (user.getStatus() == 0) {
                return R.error("用户账号已被冻结!");
            }
            //判断用户是否被删除
            if (user.getDelFlag() == "1") {
                return R.error("用户已被删除");
            }
        } else {
            return R.error("账号或密码错误");
        }

        //将结果返还给前端 将用户id和用户名存入 token
        Map tokenMap = new HashMap();
        tokenMap.put("Userid", user.getId());
        String token = JwtUtils.getToken(tokenMap);

        Map resToken = new HashMap();
        resToken.put("token", token);
        return R.success(resToken);
    }


    @GetMapping("/baseInfo")
    public ResultData baseInfo(){
        return loginService.baseInfo();
    }

    /**
     * 获取用户资料
     *
     * @param request
     * @return
     */
    @PostMapping("/profile")
    public R profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
        Long userId = Long.valueOf((String) claims.get("Userid"));

        log.info("用户id:{}", userId);
        ProFileVo profile = loginService.profile(userId);
        return R.success(profile);
    }

    /**
     * 文章列表数据
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    public R<Map> page(int page, int limit, int cateid) {
        //分页查询拦截器
        Page<YddArticle> pageInfo = new Page(page, limit);
        //条件构造器
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid, cateid);
        //查询
        yddArticleService.page(pageInfo,queryWrapper);
        List<YddArticle> records = pageInfo.getRecords();
        List<YddArticleVo> yddArticleVos = records.stream().map((yddArticle) -> {
            YddArticleVo yddArticleVo = new YddArticleVo();
            BeanUtils.copyProperties(yddArticle, yddArticleVo);
            YddCate byId = yddCateService.getById(yddArticleVo.getCateid());
            yddArticleVo.setCatename(byId.getCatename());
            return yddArticleVo;
        }).collect(Collectors.toList());

        PageDto pageDto = new PageDto();
        pageDto.setPageSize(limit);
        pageDto.setCurrentPage(page);
        pageDto.setCount((int)pageInfo.getTotal());
        pageDto.setTotalPages((int)pageInfo.getPages());
        pageDto.setData(yddArticleVos);

//        List<PageDto> pageDtos = new ArrayList<>();
//        pageDtos.add(pageDto);
        Map<String, Object> ret = new HashMap<>();
        ret.put("list", pageDto);

        return R.success(ret);
    }

    /**
     * 注册
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public R<String> add(@RequestBody YddUser yddUser) {
        log.info("用户注册信息" + yddUser);

        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, yddUser.getMobile());
        YddUser user1 = yddUserService.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(user1)) {
            throw new CustomException("账号已经存在!");
        }

        //接收前端发来的密码  将密码经md5处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        String mobile = yddUser.getMobile();

        //封装用户信息
        YddUser user = new YddUser();
        user.setPassword(password);
        user.setMobile(mobile);
        user.setUsername(mobile);

        yddUserService.save(user);

        return R.success("注册成功!");
    }

    /**
     * 热门置顶文章数据(首页)
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public ResultData New(int page, int limit) {

        //构造分页构造器对象
        Page<YddArticle> pageInfo = new Page(page, limit);

        NewVo res = yddArticleService.selectByPage(pageInfo);

        return ResultData.ok("", res);
    }

    /**
     * 最新文章
     *
     * @return
     */
    @GetMapping("/hot")
    public ResultData Hot() {

        //YddArticle  Cate 组合信息
        HotVo yddArticlesCate = yddArticleService.YddArticleCatelist();

        return ResultData.ok("", yddArticlesCate);
    }

    /**
     * 推荐文章
     *
     * @return
     */
    @GetMapping("/recommend")
    public ResultData recommend() {

        //YddArticle  Cate 组合信息
        HotVo yddArticlesCate = yddArticleService.YddArticleCatelist();

        return ResultData.ok("", yddArticlesCate);
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public ResultData Index() {

        IndexVo res = loginService.selectIndex();

        return ResultData.ok("",res);
    }

    /**
     * 展示文章详细信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/show")
    public R<ShowDto> show(Integer id, HttpServletRequest request) {
        ShowDto showDto = new ShowDto();
        //获取当前用户id
        Integer userId = yddUserService.getUserId(request);
        //获取文章信息
        YddArticle article = yddArticleService.getById(id);
        //
        YddArticleDto yddArticleDto = new YddArticleDto();
        BeanUtils.copyProperties(article,yddArticleDto);
        //获取点赞信息
        LambdaQueryWrapper<YddUserData> dianQueryWrapper = new LambdaQueryWrapper<>();
        dianQueryWrapper.eq(YddUserData::getUserId, userId);
        dianQueryWrapper.eq(YddUserData::getArticleId, article.getId());
        List<YddUserData> yddUserDataList = yddUserDataService.list(dianQueryWrapper);
        if(!CollectionUtils.isEmpty(yddUserDataList)){
            for (YddUserData yddUserData : yddUserDataList) {
                Integer idd = yddUserData.getType();
                if(idd==1){
                    yddArticleDto.setCollect(true);
                }else if(idd==2){
                    yddArticleDto.setLike(true);
                }

            }
        }else {
            yddArticleDto.setLike(false);
            yddArticleDto.setCollect(false);
        }
        //获取分类名称
        YddCate yddCate = yddCateService.getById(yddArticleDto.getCateid());
        String cateName= yddCate.getCatename();
        yddArticleDto.setCateName(cateName);

        showDto.setInfo(yddArticleDto);
        //获取上一篇信息
        List<HashMap> prev = new ArrayList<>();
        YddArticle article1 = yddArticleService.getById(id-1);
        if(article1!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id-1));
            map.put("title",article1.getTitle());
            prev.add(map);
        }
        showDto.setPrev(prev);
        //获取下一篇信息
        List<HashMap> next = new ArrayList<>();
        YddArticle article2 = yddArticleService.getById(id+1);
        if(article1!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("id",(id+1));
            map.put("title",article2.getTitle());
            prev.add(map);
        }
        showDto.setNext(next);
        //获取推荐信息
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid,yddArticleDto.getCateid()).last("limit 8");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        showDto.setRecommend(list);

        return R.success(showDto);

    }

    @GetMapping("/getConfig")
    public R<Map> getConfig() {
        Map<String, String> map = new HashMap<>();
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(queryWrapper);
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }
        return R.success(map);
    }
}